const inquirer = require("inquirer");
const process = require("process");
const chalk = require("chalk");
const fs = require("fs");
const download = require("download-git-repo");
const { cyan } = require("chalk");

const writeFile = (filePath, projectName) => {
  fs.readFile(filePath, "utf8", (err, data) => {
    if (err) throw err;
    let dataSource = JSON.parse(data);
    dataSource.name = projectName;
    if (dataSource.projectName) {
      dataSource.projectName = projectName;
    }
    if (dataSource.description) {
      dataSource.description = projectName;
    }
    fs.writeFileSync(filePath, JSON.stringify(dataSource));
  });
};

module.exports = {
  //检查文件是否存在
  async checkFile(name, callback) {
    const { action } = await inquirer.prompt({
      message: "新建文件已存在,请选择：",
      type: "list",
      name: "action",
      choices: [
        {
          name: `删除 ${name}, 并重写`,
          value: "overwrite",
        },
        {
          name: "取消",
          value: false,
        },
      ],
    });
    if (!action) {
      return;
    }
    if (action === "overwrite") {
      console.log(`\n删除 ${chalk.cyan(name)}...`);
      await delDir(process.cwd() + "/" + name);

      function delDir(path) {
        let files = [];
        if (fs.existsSync(path)) {
          files = fs.readdirSync(path);
          files.forEach((file, index) => {
            let curPath = path + "/" + file;
            if (fs.statSync(curPath).isDirectory()) {
              delDir(curPath); //递归删除文件夹
            } else {
              fs.unlinkSync(curPath); //删除文件
            }
          });
          fs.rmdirSync(path);
        }
      }
      callback();
    }
  },

  //下载模版并重写package.json的名称
  async downloadFile(projectName, cmd_order, callback) {
    console.log(chalk.cyan("拉取远程模板中..."));
    //模版地址和关键字${cmd_order}
    download(
      `direct:code_address/${cmd_order}-template.git`, //模版地址
      projectName,
      {
        clone: true,
      },
      async (error) => {
        if (error) {
          console.log(error);
          console.log(chalk.red("拉取远程模板仓库失败！"));
          return;
        }
        const filePath = process.cwd() + `/${projectName}/package.json`;
        writeFile(filePath, projectName);
        // 小程序处理
        if (cmd_order === "weapp") {
          const projectFilePath =
            process.cwd() + `/${projectName}/project.config.json`;
          const projectFilePath_prod =
            process.cwd() + `/${projectName}/project.config.prod.json`;
          writeFile(projectFilePath, projectName);
          writeFile(projectFilePath_prod, projectName);
        }
        callback();
      }
    );
  },
};
